package test;

import com.netflix.hystrix.*;

/**
 * describe:
 *
 * @author helloworldyu
 * @date 2018/11/16
 */
public class CircuitCommand extends HystrixCommand<String> {
	private static final HystrixCommandGroupKey GROUP_KEY = HystrixCommandGroupKey.Factory.asKey("CircuitCommamd");

	private static final HystrixCommandKey COMMAND_KEY = HystrixCommandKey.Factory.asKey("CircuitCommand");

	private static final HystrixThreadPoolKey THREAD_POOL_KEY = HystrixThreadPoolKey.Factory.asKey("CircuitThread");


	protected CircuitCommand(){
		this(HystrixCommandProperties.Setter()
			.withCircuitBreakerEnabled(true)
			//任务超时时间
			.withExecutionTimeoutInMilliseconds(3000)
			//计算成功失败百分比的时间间隔，默认500ms
			.withMetricsRollingStatisticalWindowInMilliseconds(6000)
			//判断熔断的最少请求数，默认是20，只有在一个统计窗口内处理的请求数量达到这个阈值，才会进行是否熔断的判断
			.withCircuitBreakerRequestVolumeThreshold(5));
	}

	protected CircuitCommand(HystrixCommandProperties.Setter setter) {
		super(HystrixCommand.Setter.withGroupKey(GROUP_KEY)
			.andCommandKey(COMMAND_KEY)
			.andThreadPoolKey(THREAD_POOL_KEY)
			.andCommandPropertiesDefaults(setter));
	}

	@Override
	protected String run() throws Exception {
		try {
			System.out.println("没有被熔断");
			Thread.sleep(1000);
			throw new RuntimeException("测试");
		}catch (Exception e){
			System.out.println("异常被捕获");
		}
		return "ok";
	}

//	@Override
//	protected String run() throws Exception {
//		System.out.println("没有被熔断");
//		Thread.sleep(1000);
//		throw new RuntimeException("测试");
//	}

	@Override
	protected String getFallback() {
		return "快速失败";
	}

	public static void main(String[] args) {
		final int taskNum = 100;

		for ( int i=0; i<taskNum; ++i ){
			CircuitCommand circuitCommand = new CircuitCommand();
			String execute = circuitCommand.execute();
			System.out.println("i=" + i + " result:" + execute);
		}
	}
}




